<template>
  <div class="common-list-view__v2">
    <div class="common-list-view-header__v2 a-center mb_12">
      <div class="common-list-view-header__v2-left">
      </div>
      <div class="common-list-view-header__v2-right">
        <slot name="time"></slot>
         <el-dropdown>
          <span class="el-dropdown-link cur-point acenter">
            {{ $t('common.base.moreOperator') }}
            <i class="iconfont icon-fdn-select ml_4"></i>
          </span>
           <el-dropdown-menu slot="dropdown">
             <el-dropdown-item>
               <div @click="handleExport(false)">{{$t('common.base.export')}}</div>
             </el-dropdown-item>

             <el-dropdown-item>
               <div @click="handleExport(true)">{{$t('common.base.exportAll')}}</div>
             </el-dropdown-item>
           </el-dropdown-menu>
        </el-dropdown>

        <div class="el-dropdown-link cur-point acenter" @click="handleSelectColumn">
          {{ $t('common.base.choiceCol') }}
          <i class="iconfont icon-fdn-select ml_4"></i>
        </div>
      </div>
    </div>

    <el-table
      v-if="columns.length"
      v-loading="loading"
      ref="tableComponentRef"
      header-row-class-name="common-list-table-header__v2"
      class="bbx-normal-list-box"
      :data="dataList"
      :height="tableContainerHeight"
      @select="handleSelection($event, dataList)"
      @select-all="handleSelection($event, dataList)"
      @header-dragend="handlerHeaderDragend"
      stripe
      border
    >
      <el-table-column type="selection" width="48" align="center"></el-table-column>
      <template v-for="column in columns">
        <el-table-column
          v-if="column && column.show"
          :align="column.align"
          :key="column.fieldName"
          :label="column.displayName"
          :prop="column.fieldName"
          :width="column.width || 160"
          :min-width="column.minWidth"
          :sortable="column.sortable"
          :fixed="column.fixLeft || false"
          show-overflow-tooltip
        >
          <template slot-scope="{ row }">
            <!-- 备件编号 -->
            <template v-if="column.fieldName === 'sparepartNo'">
              <div class="link-text" @click="openSparepartNoViewTab(row)">{{ row.sparepartNo }}</div>
            </template>
            <!-- 工单编号 -->
            <template v-else-if="column.fieldName === 'taskNo'">
              <div class="link-text" @click="openTaskNoViewTab(row)">{{ row.taskNo }}</div>
            </template>
            <!-- 服务内容 -->
            <template v-else-if="column.fieldName === 'serviceContentText'">
              <div>{{ row.serviceContent }}</div>
            </template>
            <!-- 服务部门 -->
            <template v-else-if="column.fieldName === 'serviceTag'">
              <div>{{ row.serviceTag }}</div>
            </template>
            <!-- 负责人 -->
            <template v-else-if="column.fieldName === 'executor'">
              <div>{{ row.executor }}</div>
            </template>
            <!-- 申领人 -->
            <template v-else-if="column.fieldName === 'claimant'">
              <div>{{ row.claimant }}</div>
            </template>
            <template v-else>
              {{ $formatFormField(column, row) }}
            </template>
          </template>
        </el-table-column>
      </template>

      <template slot="empty">
        <BaseListForNoData  v-show="!loading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
      </template>
    </el-table>

    <!-- 分页 S -->
    <div class="table-footer bbx-normal-table-footer-10">
      <div class="list-info">
        <i18n path="common.base.table.totalCount">
          <span place="count" class="level-padding">{{ dataListPageInfo.total || 0 }}</span>
        </i18n>

        <template v-if="multipleSelection.length > 0">
          <i18n path="common.base.table.selectedNth">
            <span place="count" class="color-primary pad-l-5 pad-r-5">{{ multipleSelection.length }}</span>
          </i18n>
          <span class="color-primary pad-l-5 cur-point" @click="clearSelection">{{ $t('common.base.clear') }}</span>
        </template>
      </div>

      <el-pagination
        background
        @current-change="handlePageNumChange"
        @size-change="handleSizeChange"
        :page-sizes="defaultTableData.defaultPageSizes"
        :page-size="searchParams.pageSize"
        :current-page="searchParams.pageNum"
        layout="prev, pager, next, sizes, jumper"
        :total="dataListPageInfo.total"
      >
      </el-pagination>
    </div>
    <!-- 分页 E -->
  </div>
</template>

<script>
/* model */
import { ViewTypeComponentNameEnum } from '@src/modules/partV2/occupyList/model';
/* hooks */
import { useTable } from '@src/modules/projectManage/projectManageList/hooks/useTable';
import { useFetchOccupyTableList } from '@src/modules/partV2/occupyList/hooks/useFetch';
/* vue */
import { ref, reactive, onMounted, watch, computed } from 'vue';
/* util */
import { defaultTableData } from '@src/util/table'
import i18n from "@src/locales";
import {toast, alert, openAccurateTab} from "@src/util/platform";
import { showExportListAlert } from "@src/util/alert";
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

/* const*/
const MAX_COUNT = 999999999;
/* api */
import { exportSparepartOccupancy } from '@src/api/SparePart';
export default {
  name: 'OccupyTableList',
  props: {
    columns: {
      type: Array,
      default: () => ([])
    },
    params: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props, { emit }) {
    const { tableComponentRef, multipleSelection, handleSelection, clearSelection, matchSelected, disposeHeaderDragendColumns, selectedIds } = useTable();
    const { loading, dataList, dataListPageInfo, fetchTaskManageTableList } = useFetchOccupyTableList();

    // 表格高度
    const tableContainerHeight = ref('calc(100% - 100px)');

    // 搜索参数
    const searchParams = reactive({
      pageSize: 10,
      pageNum: 1,
    })

    // 选择列
    const handleSelectColumn = () => {
      emit('handleSelectColumn');
    }

    // 表头拖动列改变宽度
    const handlerHeaderDragend = (newWidth, oldWidth, column) => {
      disposeHeaderDragendColumns(newWidth, column, props.columns, ViewTypeComponentNameEnum.Table);
    }

    // 搜索
    const search = (isRefresh) => {
      // 需要刷新
      if (isRefresh) return handlePageNumChange(1);
      
      const params = {
        ...searchParams,
        ...props.params
      }

      fetchTaskManageTableList(params);
    }

    // 页码跳转
    const handlePageNumChange = (pageNum) => {
      searchParams.pageNum = pageNum;
      dataList.value = [];
      search();
    }

    // 分页条数改变
    const handleSizeChange = (pageSize) => {
      searchParams.pageSize = pageSize;
      searchParams.pageNum = 1;
      search();
    }

    // 导出 & 导出全部（不弹框去选择字段导出，直接导出-找天权）
    const handleExport = async (isExportAll) => {
      try {
        let ids = [];

        // 校验
        if (!isExportAll) {
          if (!multipleSelection.value.length) {
            return toast(i18n.t('common.base.tip.exportNoChoice'), 'warning');
          }
          ids = selectedIds.value;
        } else if (isExportAll && dataListPageInfo.value.total > MAX_COUNT) {  // 检测导出条数

          return toast(i18n.t('common.base.tip.exportLimit'), 'warning');
        }

        // 导出
        const params = {
          ...searchParams,
          ...props.params,
          ids,
          totalCount: isExportAll ? dataListPageInfo.value.total : selectedIds.value.length,
        }

        // 导出所有，移除pageSize参数
        if(isExportAll) delete params.pageSize

        let { success, message} = await exportSparepartOccupancy(params);
        if (success) {
          showExportListAlert(message)
        }else{
          alert(message);
        }

      } catch (e) {
        console.error(e)
      }
    };

    // 备件详情
    function openSparepartNoViewTab(row) {
      openAccurateTab({
        type: PageRoutesTypeEnum.PagePartCategoryDetail,
        key: row.sparepartId,
        params: `id=${row.sparepartId}`,
      })
    }

    function openTaskNoViewTab(row) {
      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: row.taskId,
        titleKey: row.taskNo,
        fromId,
      })
    }

    // 监听列表数据 把选中的匹配出来
    watch(dataList, (newValue) => {
      matchSelected(newValue);
    })

    onMounted(() => {
      search(true);
    })

    return {
      defaultTableData,
      loading,
      dataList,
      dataListPageInfo,
      tableContainerHeight,
      searchParams,

      tableComponentRef,
      multipleSelection,
      handleSelection,
      clearSelection,
      handlerHeaderDragend,

      handleSelectColumn,
      handlePageNumChange,
      handleSizeChange,
      search,

      handleExport,
      openSparepartNoViewTab,
      openTaskNoViewTab,
    };
  },
};
</script>

<style lang="scss" scoped>
.common-list-view__v2 {
  height: 100%;
}

.import-task {
  position: relative;
  left: -15px;
  padding-left: 15px;

  &:hover &-item {
    display: block;
  }

  &-item {
    position: absolute;
    background: #fff;
    color: $text-color-primary;
    left: -115px;
    top: -8px;
    border: 1px solid #eee;
    border-radius: 4px;
    max-height: 50vh;
    overflow-y: auto;
    display: none;

    >div {
      padding: 4px 15px;
      width: 120px;
      word-break: break-all;

      &:hover {
        background-color: $color-regular;
        color: #77c5c3;
      }
    }
  }
}

.el-table {
  .status-tag {
    padding: 0 8px;
    background-color: $color-ding-blue;
    line-height: 22px;
    border-radius: 22px;
    color: #fff;
    font-size: 12px;
  }

  .el-progress {
    width: 100%;
  }
}
</style>

